﻿using System.Linq;
using System.Xml;

using MonPocGarage.ArmyContracts;
using MonPocGarage.ArmyContracts.Common.Enums;
using MonPocGarage.Common.Extensions;

namespace MonPocGarage.GUI.Helpers
{
    public static class ArmyInstance
    {
        public static Army GetArmy(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return new Army();
            }
            Army getArmy = new Army();
            var monsterList = BuildArmy.GetMonsters();
            var unitList = BuildArmy.GetUnits();
            var buildingList = BuildArmy.GetBuildings();

            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(fileName);

            Faction armyFaction = xDoc.SelectSingleNode("Army/ArmyFaction").InnerText.ToEnumValue<Faction>();
            string armyName = xDoc.SelectSingleNode("Army/ArmyName").InnerText;

            getArmy.ChangeArmyFaction(armyFaction);
            getArmy.ChangeArmyName(armyName);

            foreach (XmlNode xNode in xDoc.SelectNodes("Army/Monsters/MonsterID"))
            {
                Monster getMonster = monsterList.Where(m => m.MonsterID == xNode.InnerText).FirstOrDefault();
                if (getMonster != null)
                {
                    getArmy.AddMonster((Monster) getMonster.Clone());
                }
            }
            foreach (XmlNode xNode in xDoc.SelectNodes("Army/Units/UnitID"))
            {
                Unit getUnit = unitList.Where(m => m.UnitID == xNode.InnerText).FirstOrDefault();
                if (getUnit != null)
                {
                    getArmy.AddUnit((Unit) getUnit.Clone());
                }
            }
            foreach (XmlNode xNode in xDoc.SelectNodes("Army/Buildings/BuildingID"))
            {
                Building getBuilding = buildingList.Where(m => m.BuildingID == xNode.InnerText).FirstOrDefault();
                if (getBuilding != null)
                {
                    getArmy.AddBuilding((Building) getBuilding.Clone());
                }
            }
            return getArmy;
        }
    }
}
